package com.bailv.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.json.JSONException;
import org.json.JSONObject;

import com.bailv.macro.SensorNameMacro.SensorName;

import android.util.Log;

import com.bailv.macro.YeelinkSensorID;

public class Yeelink implements Runnable{

	private static final String apiUrl = "http://api.yeelink.net/v1.0/device/69195/sensor/";
	private static String ApiKey = "5f8fdc543f5362b6adbeef6532e68313";

	private SensorName sensorName;
	private boolean action;

	public Yeelink(SensorName sensorName, boolean action) {
		this.sensorName = sensorName;
		this.action = action;
	}

	private void sendPost() {

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(apiUrl + YeelinkSensorID.getSensorID(sensorName) + "/datapoints");
		// ͷ
		httpPost.addHeader("U-ApiKey", ApiKey);

		JSONObject jsonObject = new JSONObject();

		try {

			jsonObject.put("value", action ? 1 : 0);
			httpPost.setEntity(new StringEntity(jsonObject.toString()));
			Log.d("YeelinkJson", jsonObject.toString());
			HttpResponse response = httpClient.execute(httpPost);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				Log.d("Yeelinkrequst", "ok");
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		sendPost();
	}
	
}
